package com.bybops.ui.activity

import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.view.View
import baseproject.com.mybaseproject.ui.base.BaseActivity
import baseproject.com.mybaseproject.utils.scheduler.RxUtils
import com.bybops.R
import com.uuzuche.lib_zxing.activity.CaptureFragment
import com.uuzuche.lib_zxing.activity.CodeUtils
import kotlinx.android.synthetic.main.activity_scan.*
import kotlinx.android.synthetic.main.toolbar_base.*
import kotlinx.android.synthetic.main.toolbar_base.view.*

class ScanActivity : BaseActivity() {

    private val captureFragment : CaptureFragment = CaptureFragment()
    //是否开启闪光灯
    private var flashlight = false

    override fun getLayoutId(): Int? {
        return R.layout.activity_scan
    }
    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar?.titleBar(R.id.mToolBar)
                ?.navigationBarColor(R.color.colorPrimaryDark)
                ?.init()
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //为二维码扫描界面设置定制化界面
        CodeUtils.setFragmentArgs(captureFragment , R.layout.my_camera)
        captureFragment.analyzeCallback = analyzeCallback
        supportFragmentManager.beginTransaction().replace(R.id.fl_my_container, captureFragment).commit()
        initView()
    }


    private fun initView() {
        mToolBar.setBackgroundResource(R.color.transparent)
        mToolBar.mTitle.visibility = View.GONE
        mToolBar.mBtnBack.setImageResource(R.mipmap.scan_close)
        RxUtils.rxClick(mToolBar.mBtnBack , object : RxUtils.OnClickInterf{
            override fun onViewClick(view: View) {
               finish()
            }
        })
        RxUtils.rxClick(tvSgd , object : RxUtils.OnClickInterf{
            override fun onViewClick(view: View) {
                CodeUtils.isLightEnable(!flashlight)
                flashlight = !flashlight
            }
        })
    }

    /**
     * 二维码解析回调函数
     */
    private val analyzeCallback: CodeUtils.AnalyzeCallback = object : CodeUtils.AnalyzeCallback {
        override fun onAnalyzeSuccess(mBitmap: Bitmap, result: String) {
            val resultIntent = Intent()
            val bundle = Bundle()
            bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_SUCCESS)
            bundle.putString(CodeUtils.RESULT_STRING, result)
            resultIntent.putExtras(bundle)
            this@ScanActivity.setResult(RESULT_OK, resultIntent)
            this@ScanActivity.finish()
        }

        override fun onAnalyzeFailed() {
            val resultIntent = Intent()
            val bundle = Bundle()
            bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED)
            bundle.putString(CodeUtils.RESULT_STRING, "")
            resultIntent.putExtras(bundle)
            this@ScanActivity.setResult(RESULT_OK, resultIntent)
            this@ScanActivity.finish()
        }
    }
}